package service

import (
	"api-gateway/basic/config"
	__ "api-gateway/basic/proto/rpc"
	"api-gateway/handler/request"
	"api-gateway/pkg"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

func Register(c *gin.Context) {
	var form request.Register
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "参数错误"})
		return
	}
	user, err := config.VideoRpcClient.Register(c, &__.RegisterReq{
		Phone:    form.Phone,
		SmsCode:  form.SmsCode,
		Password: form.Password,
		Username: form.Username,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "注册失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "注册成功", "data": gin.H{
		"userId": user.UserId,
	}})
	return
}

func Login(c *gin.Context) {
	var form request.Login
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "参数错误"})
		return
	}
	user, err := config.VideoRpcClient.Login(c, &__.LoginReq{
		Phone:   form.Phone,
		SmsCode: form.SmsCode,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "登录失败"})
		return
	}
	token, err := pkg.GetJwtToken(int(user.UserId))
	if err != nil {
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "登录成功", "data": gin.H{
		"userId": user.UserId,
		"token":  token,
	}})
	return
}

func SendSms(c *gin.Context) {
	var form request.SendSms
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "参数错误"})
		return
	}
	sms, err := config.VideoRpcClient.SendSms(c, &__.SendSmsReq{
		Phone: form.Phone,
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": err.Error()})
		return
	}
	log.Println(sms)
	c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "验证码发送成功", "data": gin.H{}})
	return
}
